package com.brightness.security.oauth2.server.config.service;

import com.brightness.security.oauth2.server.domain.TbPermission;
import com.brightness.security.oauth2.server.domain.TbUser;
import com.brightness.security.oauth2.server.service.TbPermissionService;
import com.brightness.security.oauth2.server.service.TbUserService;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
/**
 * @author: mailtohgh@163.com
 * @date: 2019/12/30
 * @time: 3:42 下午
 * @descript:
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private TbUserService userService;

    @Autowired
    private TbPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TbUser tbUser = userService.selectByUsername(username);
        if (tbUser==null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        List<TbPermission> tbPermissions = permissionService.selectByUserId(tbUser.getId());
        tbPermissions.forEach(tbPermission -> grantedAuthorities.add(new SimpleGrantedAuthority(tbPermission.getEnname())));
        return new User(tbUser.getUsername(),tbUser.getPassword(),grantedAuthorities);
    }
}
